﻿using HpApi.Types;
using Network;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.AppService;
using Windows.Foundation.Collections;
using Windows.Security.ExchangeActiveSyncProvisioning;
using Xiaowei.Helpers;
using Xiaowei.Settings;
using Log = Logger.Debug;
namespace Xiaowei.Services
{
    public class LicenseService
    {
        private LicenseService()
        {
            Connectivity.AvailabilityChanged += (availability) => {
                GetLicense();
            };
        }
        private static readonly Lazy<LicenseService> LazyInstance = new Lazy<LicenseService>(() =>
        {
            return new LicenseService();
        }, LazyThreadSafetyMode.ExecutionAndPublication);

        public static LicenseService Instance { get { return LazyInstance.Value; } }

        public bool IsInit { get; private set; } = false;
        public bool GetSerialNumberEnd { get; private set; } = false;
        public bool GetLicenseEnd { get; private set; } = false;
        public event Action InitEnded;
        public event Action<bool> FetchSerialNumberEnded;
        public event Action<bool> FetchLicenseEnded;
        public void Init()
        {
            if (IsInit) return;
            IsInit = true;
            GetLicense();
            
        }

        public async void GetLicense()
        {
            FetchSerialNumber();
            if (Connectivity.IsAvailable)
            {
                await FetchLicense().ConfigureAwait(false); 
            }
        }


        private void FetchSerialNumber()
        {
            if (GetSerialNumberEnd) return;
            var value = new ValueSet() { { "Request", "SerialNumber" } };
            var serialNumber = ServiceFactory.DeviceInfoService.SerialNumber;
            var ssid = ServiceFactory.DeviceInfoService.SSID;
            var deviceName = ServiceFactory.DeviceInfoService.DeviceName;
            var productNumber = ServiceFactory.DeviceInfoService.ProductNumber;
            var systemVersion = ServiceFactory.DeviceInfoService.SystemVersion;
            if (serialNumber is string sn && ssid is string s && deviceName is string dev && productNumber is string pn && systemVersion is string sv)
            {
                LocalSettings.SerialNumber = sn;
                LocalSettings.SSID = s;
                LocalSettings.DeviceName = dev;
                if (DebugConfig.SSID.Length > 0)
                {
                    LocalSettings.SSID = DebugConfig.SSID;
                }
                if (string.IsNullOrEmpty(pn))
                {
                    EasClientDeviceInformation easClientDeviceInformation = new EasClientDeviceInformation();
                    pn = easClientDeviceInformation.SystemSku;
                    if (!string.IsNullOrEmpty(pn))
                    {
                        try
                        {
                            LocalSettings.ProductNumber = pn.Substring(0, pn.IndexOf('#'));
                        }
                        catch (Exception)
                        {

                            LocalSettings.ProductNumber = "";
                        }

                    }
                    else
                    {
                        LocalSettings.ProductNumber = "";
                    }
                }
                else
                {
                    LocalSettings.ProductNumber = pn;
                }
                LocalSettings.SystemVersion = sv;
                GetSerialNumberEnd = true;
                FetchSerialNumberEnded?.Invoke(true);
                return;
            }
            FetchSerialNumberEnded?.Invoke(false);
        }

        private async Task FetchLicense()
        {
            if (!GetSerialNumberEnd) return;
            if (GetLicenseEnd) return;
            string sn = LocalSettings.SerialNumber;
            string ssid = LocalSettings.SSID;
            Log.WriteLine("FetchLicense");
            sn = WindowsIdentity.GetCurrent().Name + "\\" + sn;
            if (DebugConfig.SnDebugEnabled)
            {
                sn = "DEBUG" + sn;
            }

            if (Connectivity.IsAvailable)
            {
                var token = await ServerApi.Instance.InitAsync(sn, ssid).ConfigureAwait(false);
                if (token != null)
                {
                    //first stage enabled
                    bool fsEnabled = !(ServerApi.WakeupType == PlatformWakeupType.HwWithoutSSKWS ||
                                       ServerApi.WakeupType == PlatformWakeupType.HwWithSSKWS);
                    //second stage enabled
                    bool ssEnabled = ServerApi.WakeupType == PlatformWakeupType.SwWithSSKWS ||
                                     ServerApi.WakeupType == PlatformWakeupType.HwWithSSKWS;


                    MVAWakeUpService.Instance.SetEnableStageKws(fsEnabled,ssEnabled);
                    ServerApi.SN = sn;
                    ServerApi.SSID = ssid;
                    ServerApi.Token = token;

                    LocalSettings.Guid = ServerApi.Instance.Signature.Guid;
                    LocalSettings.License = ServerApi.Instance.Signature.Sign;
                    LocalSettings.ProductId = Convert.ToInt32(ServerApi.Instance.Signature.ProductId);
                    LocalSettings.AppId = ServerApi.Instance.Signature.AppId;
                    LocalSettings.KeyVersion = ServerApi.Instance.Signature.KeyVersion;
                    GetLicenseEnd = true;
                    
                    FetchLicenseEnded?.Invoke(true);
                    InitEnded?.Invoke();
                    return;
                }
            }
            FetchLicenseEnded?.Invoke(false);
        }

    }
}
